import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';

/// 未完成 哈哈
class ExportCanvas extends StatefulWidget {
  const ExportCanvas({super.key});

  @override
  State<ExportCanvas> createState() => _ExportCanvasState();
}

class _ExportCanvasState extends State<ExportCanvas> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('export canvas'),
      ),
      body: Column(
        children: <Widget>[
          AspectRatio(
            aspectRatio: 1,
            child: Image.network(
              'https://cdn.jsdelivr.net/gh/kikt-blog/image/img/2019-05-31%20at%2016.05.png',
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              final now = DateTime.now();
              final pr = PictureRecorder();
              final canvas = Canvas(pr, const Rect.fromLTWH(0, 0, 1400, 960));
              writeSomeThings(canvas);
              final pic = pr.endRecording();
              final img = await pic.toImage(1400, 960);
              final byteData =
                  await img.toByteData(format: ImageByteFormat.png);
              final result = byteData?.buffer.asUint8List();
              print(Directory.current);
              if (result != null) {
                final f = File('${Directory.current.path}/test.png');
                f.writeAsBytesSync(result, mode: FileMode.write);
                print(f.absolute.path);
                final diff = DateTime.now().difference(now);
                print(diff.inMilliseconds);
              }
            },
            child: const Text(''),
          ),
        ],
      ),
    );
  }

  void writeSomeThings(Canvas canvas) {
    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;
    canvas.drawCircle(
      Offset.zero,
      30,
      paint,
    );
  }
}
